package com.gmlive.common.imageloader

import android.app.Application
import android.graphics.Bitmap
import android.net.Uri
import com.facebook.common.util.UriUtil
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.core.ImagePipelineConfig
import com.gmlive.common.imageloader.request.RequestCreate
import com.gmlive.common.imageloader.url.UrlCreate
import java.io.File

/**
 *  Create by: fanfeiyue
 *  on: 2019-11-20
 *  desc:
 */
object ImageLoader {

    internal var IMAGE_SCALE_URL: String? = null
    internal lateinit var app: Application

    fun init(context: Application, imageScaleUrl: String?) {
        init(context, imageScaleUrl, null)
    }

    fun init(context: Application, imageScaleUrl: String?, config: ImagePipelineConfig?) {
        IMAGE_SCALE_URL = imageScaleUrl
        app = context
        Fresco.initialize(app, config)
    }

    fun load(url: String?): UrlCreate {
        requireNotNull(url) { "url must not be null" }
        return UrlCreate(url)
    }

    fun load(file: File?): RequestCreate {
        requireNotNull(file) { "file must not be null" }
        if (!file.exists()) {

        }
        return RequestCreate(Uri.fromFile(file))
    }

    fun load(resId: Int?): RequestCreate {
        requireNotNull(resId) { "localUrl must not be null" }
        return RequestCreate(Uri.Builder().scheme(UriUtil.LOCAL_RESOURCE_SCHEME).path(resId.toString()).build())
    }

    fun loadLocal(localUrl: String?): RequestCreate {
        requireNotNull(localUrl)
        return RequestCreate(Uri.Builder().scheme(UriUtil.LOCAL_FILE_SCHEME).path(localUrl).build())
    }

    fun loadAssets(assUrl: String?): RequestCreate {
        requireNotNull(assUrl) { "assUrl must not be null" }
        return RequestCreate(Uri.Builder().scheme(UriUtil.LOCAL_ASSET_SCHEME).path(assUrl).build())
    }


}

fun Int.dip2px(): Int {
    val scale = ImageLoader.app.resources?.displayMetrics?.density ?: 0F
    return (this * scale + 0.5F).toInt()
}

/**
 * 判断bitmap是否可用 不能为空 不能是已经被回收的 isRecycled返回false
 */
fun Bitmap?.isAvailable(): Boolean {
    return null != this && "" != this.toString() && !this.isRecycled
}
